<?php
class Admin extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->helper(array('form', 'url'));

		$this->load->model('Post_model');
	}

	function index()
	{
		if (!$this->session->userdata('admin')) { // not logged in?
			redirect('/admin/login', 'location');
			return;
		} else {
			if (!$this->input->post('approved')) { // list posts to approve
				$data['posts'] = $this->Post_model->get_unapproved_posts();
				$this->load->view('admin_approve_posts', $data);
				
			} else { // process approved posts submitted
				foreach ($this->input->post('approved') as $post) {
					$this->Post_model->approve($post);
				}
				redirect('/admin', 'location');
			}
		}
	}
	
	function disapprove($id) {
		if (!$this->session->userdata('admin')) { // not logged in?
			redirect('/admin/login', 'location');
			return;
		} else {
			$this->Post_model->disapprove($id);
			redirect('/admin', 'location');
		}
	}
	
	function login()
	{
		if (!$this->input->post('username')) 
		{
			$this->load->view('admin_login');
		} 
		else // process form
		{
			$encryptedPassword = '$1$H20.Ex..$fNYXGR/AsHVzsDQ5dO6In0';
 			if (($this->input->post('username') == "mrdx") && (crypt($this->input->post('password'), $encryptedPassword) == $encryptedPassword))
			{
				$this->session->set_userdata('admin', true);
				redirect('/admin', 'location');
			}
			else {
				redirect('/', 'location');
			}
		}
	}

}
